<template>
    <div>
        <div class="top-img">
            <img style="width: 100%" src="https://img.js.design/assets/img/617766b867e5da8dd2a409b5.png" alt="">
        </div>
        <div class="bottom-content">
            <el-card>
                <el-page-header title="返回" content="编辑信息" @back="goBack" />
            </el-card>
            <el-card>
                <el-form
                        v-show="!is_sign_up"
                        :label-position="'top'"
                        ref="updateFormRef"
                        :model="updateForm"
                        status-icon
                        :rules="updateRules"
                        label-width="120px"
                        class="demo-ruleForm"
                >
                    <el-row :gutter="2" justify="space-around">
                        <el-col :span="8">
                            <el-form-item prop="org_code">
                                <span>报名机构代码：</span><el-input :disabled="true" v-model="updateForm.org_code" autocomplete="off"/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="电子邮箱" prop="email">
                                <el-input placeholder="请输入您的电子邮箱" v-model="updateForm.email" autocomplete="off"/>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="2" justify="space-around">
                        <el-col :span="8">
                            <el-form-item label="请选择您要报读的机构" prop="">
                                <el-input :disabled="true" v-model="updateForm.org_name" autocomplete="off"/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="请您选择报读薪酬管理职业技能等级课程级别" prop="course_id">
                                <el-select
                                        style="width: 100%"
                                        :disabled="true"
                                        v-model="updateForm.course_id"
                                        placeholder="请您选择报读薪酬管理职业技能等级课程级别"
                                >
                                    <el-option
                                            v-for="item in courseList"
                                            :key="item.id"
                                            :label="item.name"
                                            :value="item.id"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="2" justify="space-around">
                        <el-col :span="8">
                            <el-form-item label="学员姓名" prop="name">
                                <el-input placeholder="请输入学员姓名" v-model="updateForm.name" autocomplete="off"/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="所在地区" prop="province">
                                <el-cascader
                                        style="width: 100%"
                                        :options="areaOptions"
                                        v-model="selectedOptions"
                                        @change="addressChange"
                                        placeholder="请选择所在地区"
                                >
                                </el-cascader>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="2" justify="space-around">
                        <el-col :span="8">
                            <el-form-item label="证件类型" prop="card_type">
                                <el-select
                                        style="width: 100%"
                                        v-model="updateForm.card_type"
                                        placeholder="请选择证件类型"
                                >
                                    <el-option
                                            v-for="item in cardOptions"
                                            :key="item.id"
                                            :label="item.name"
                                            :value="item.id"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="证件号码" prop="card_id">
                                <el-input placeholder="请输入您的证件号码" v-model="updateForm.card_id" autocomplete="off"/>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="2" justify="space-around">
                        <el-col :span="8">
                            <el-form-item label="手机号码" prop="phone">
                                <el-input placeholder="请输入您的手机号码" :disabled="true" v-model="updateForm.phone" autocomplete="off"/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">

                        </el-col>
                    </el-row>
                    <el-row justify="center" style="padding-top: 50px">
                        <el-col :span="2">
                            <el-form-item>
                                <el-button type="primary" @click="submitForm(updateFormRef)"
                                >立即修改
                                </el-button
                                >
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <div v-show="is_sign_up">
                        <el-row justify="center">
                            <el-col :sm="12" :lg="6">
                                <div style="margin: 0 auto">
                                    <el-result
                                            icon="success"
                                            title="报名成功"
                                            sub-title=""
                                    >
                                        <template #extra>
                                            <div style="display: flex">
                                                <el-button type="primary" @click="toPersonCenter">进入学员中心</el-button>
                                                <el-button @click="close">退出登录</el-button>
                                            </div>
                                        </template>
                                    </el-result>
                                </div>
                            </el-col>
                        </el-row>
                    </div>
                </el-form>
                <div v-show="is_sign_up">
                    <el-row justify="center">
                        <el-col :sm="12" :lg="6">
                            <div style="margin: 0 auto">
                                <el-result
                                        icon="success"
                                        title="报名成功"
                                        sub-title=""
                                >
                                    <template #extra>
                                        <div style="display: flex">
                                            <el-button type="primary" @click="toPersonCenter">进入学员中心</el-button>
                                            <el-button @click="close">退出登录</el-button>
                                        </div>
                                    </template>
                                </el-result>
                            </div>
                        </el-col>
                    </el-row>
                </div>
            </el-card>
        </div>
    </div>
</template>

<script>
    import Cookies from 'js-cookie'
    import {useStore} from 'vuex';
    import TencentCaptcha from "../TencentCaptcha/TencentCaptcha";
    import {reactive, ref, toRefs,toRaw} from 'vue'
    import {edit_profile, org_detail, profile, sign_up} from "../../request/api";
    import {ElMessage} from "element-plus";
    import {areaData, textToCode, codeToText} from "@/utils/JdAreaData/areaData";
    import {useRouter} from "vue-router";

    export default {
        name: "index",
        props:['updateId'],
        setup(props,{emit}) {
            let store = useStore();
            let router = useRouter();
            const updateFormRef = ref(null)

            let data = reactive({
                areaOptions: areaData, //省市区三级联动
                selectedOptions: [], //选择后的省市区对象数组
                is_sign_up:false,
                cardOptions: [
                    {id: 1, name: "居民身份证"},
                    {id: 2, name: "护照"},
                    {id: 3, name: "港澳台胞身份证"},
                ],
                courseList: [],
                updateId:null,
                updateForm: {
                    org_code: '',
                    org_name: '',
                    course_id: '',
                    name: '',
                    province: '',
                    city: '',
                    region: '',
                    card_type: 1,
                    card_id: '',
                    phone: '',
                    email:''
                },
                updateFormCopy:null
            })
            let goBack = () =>{
                router.push({path:'/user'})
            }
            let getCurrentRegister = (currentId) =>{
                profile({pid:currentId}).then(res =>{
                    console.log('当前修改信息',res)
                    data.updateId = currentId;
                    data.updateForm.name = res.name;
                    data.updateForm.org_code = res.org.org_code;
                    data.updateForm.org_name = res.org.org_name;
                    data.updateForm.course_id = res.course.name;
                    data.updateForm.email = res.email;
                    data.updateForm.card_id = res.card_id;
                    data.updateForm.phone = res.phone;
                    data.updateForm.province = res.province;
                    data.updateForm.city = res.city;
                    data.updateForm.region = res.region;
                    data.selectedOptions = textToCode([data.updateForm.province, data.updateForm.city, data.updateForm.region])
                    data.updateFormCopy = JSON.parse(JSON.stringify(data.updateForm));
                })
            }
            if(props.updateId){
                console.log('123',props.updateId);
                getCurrentRegister(toRaw(props.updateId));
            }

            const addressChange = (arr) =>{
                [data.updateForm.province, data.updateForm.city, data.updateForm.region] = codeToText(arr);
            }

            const validateOrgCode = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('机构代码不能为空'))
                } else {
                    callback()
                }
            };
            const validateCourseId = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('报读课程不能为空'))
                } else {
                    callback()
                }
            };
            const validateCardId = (rule, value, callback) => {
                if (data.updateForm.card_type == 1) {
                    let reg =
                        /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/;
                    if (value === "") {
                        callback(new Error("请填写身份证号码"));
                    } else if (!reg.test(value)) {
                        callback(new Error("身份证格式错误"));
                    } else {
                        callback();
                    }
                } else if (data.updateForm.card_type == 2) {
                    let reg = /^[A-Z,a-z,\d]+$/;
                    if (value === "") {
                        callback(new Error("请填写护照"));
                    } else if (!reg.test(value)) {
                        callback(new Error("护照格式错误"));
                    } else {
                        callback();
                    }
                } else if (data.updateForm.card_type == 3) {
                    let reg = /^[A-Z,a-z,\d]+$/;
                    if (value === "") {
                        callback(new Error("请填写港澳台胞证"));
                    } else if (!reg.test(value)) {
                        callback(new Error("证件格式错误"));
                    } else {
                        callback();
                    }
                } else {
                    callback();
                }
            };
            const validateName = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('姓名不能为空'))
                } else {
                    callback()
                }
            };
            const validateCardType = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请选择证件类型'))
                } else {
                    callback()
                }
            };
            const validatePhone = (rule, value, callback) => {
                let phoneRule = /^[1](([3][0-9])|([4][0,1,4-9])|([5][0-3,5-9])|([6][2,5,6,7])|([7][0-8])|([8][0-9])|([9][0-3,5-9]))[0-9]{8}$/;
                if (value === '') {
                    callback(new Error('手机号码不能为空'))
                } else if (!phoneRule.test(value)) {
                    callback(new Error("手机号码格式错误"))
                } else {
                    callback()
                }
            };
            const province_rule = (rule, value, callback) => {
                if (data.updateForm.province === "" || data.updateForm.province == null) {
                    callback(new Error("请选择地区"));
                } else {
                    callback();
                }
            };
            const email_rule = (rule, value, callback) => {
                let reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
                if (value === '') {
                    callback(new Error('电子邮箱不能为空'))
                } else if (!reg.test(value)) {
                    callback(new Error("电子邮箱格式错误"));
                } else {
                    callback()
                }
            };
            const updateRules = reactive({
                org_code: [{validator: validateOrgCode, trigger: 'blur'}],
                course_id: [{validator: validateCourseId, trigger: 'change'}],
                card_id: [{validator: validateCardId, trigger: 'blur'}],
                name: [{validator: validateName, trigger: 'blur'}],
                card_type: [{validator: validateCardType, trigger: 'blur'}],
                phone: [{validator: validatePhone, trigger: 'blur'}],
                province:[{validator: province_rule, trigger: 'blur'}],
                email:[{validator: email_rule, trigger: 'blur'}],
            })

            const submitForm = (formEl) => {
                if (!formEl) return
                formEl.validate((valid) => {
                    if (valid) {
                        let params = {pid:data.updateId};
                        for(let item in data.updateForm){
                           if(data.updateForm[item] != data.updateFormCopy[item]){
                               params[item] = data.updateForm[item]
                           }
                        }
                        console.log('修改参数',params)
                        edit_profile(params).then(res =>{
                            console.log(res);
                            data.is_sign_up = true;
                        })
                    } else {
                        console.log('error submit!')
                        return false
                    }
                })
            }

            const resetForm = (formEl) => {
                if (!formEl) return
                formEl.resetFields()
            }

            const toPersonCenter = () =>{
                console.log(router.currentRoute.value.name)
                if(router.currentRoute.value.name != 'User'){
                    router.push({path:'/user'})
                }else{
                    emit('toPersonCenter','personCenter')
                }
            }

            const close = () =>{
                Cookies.remove('token');
                store.commit('setToken','')
                location.reload();
            }
            return {
                goBack,
                close,
                toPersonCenter,
                addressChange,
                validatePhone,
                ...toRefs(data),
                updateFormRef,
                updateRules,
                submitForm,
                resetForm
            }
        },
        components: {
            TencentCaptcha
        }
    }
</script>

<style scoped>
    .explain{
        margin-top: 100px;
        background-color: rgba(248, 249, 251, 1);
        padding: 40px;
        border-radius: 10px;
    }
    .top-img {
        height: 260px;
        position: relative;
        overflow: hidden;
        border-top-left-radius: 10px;
        border-top-right-radius: 10px;
    }

    .top-img img {
        position: absolute;
        left: 0;
        top: -75%;
    }

    .bottom-content {
        margin-top: 50px;
    }

    .searchOrg {

    }
    .searchOrg > h2 {
        text-align: center;
        padding: 60px 0px;
    }

    .searchOrg-button {
        text-align: center;
    }

    .orgLockDiv {
        padding: 40px;
    }
</style>
